package com.kdzy.lshy.socity_server.common.wechart;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 数据签名校验
 *
 * @author cly
 * @since 2018-06-21
 *
 */
public class SignatureUtil {

	public static void main(String[] args) {
		// test
		String signature = "75e81ceda165f4ffa64f4068af58c64b8f54b88c";
		String rawData = "{\"nickName\":\"Band\",\"gender\":1,\"language\":\"zh_CN\",\"city\":\"Guangzhou\",\"province\":\"Guangdong\",\"country\":\"CN\",\"avatarUrl\":\"http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0\"}";
		String session_key = "HyVFkGl5F5OQWJZZaNzBBg==";
		boolean b = checkSignature(signature, rawData, session_key);
		System.out.println("SHA1验证结果：" + b);
	}

	/**
	 * 验证签名
	 *
	 * @param signature 微信返回的加密签名  signature = sha1( rawData + session_key )
	 * @param rawData 为校验而生
	 * @param session_key 用户的session_key
	 * @return
	 */
	public static boolean checkSignature(String signature, String rawData, String session_key ) {
		boolean isEqual = false;

		String[] arr = new String[] {rawData, session_key };

		if (rawData != null && session_key != null) {
			// 将rawData和session_key组合成一个字符串
			String content = rawData + session_key;

			// 进行SHA1加密，返回16进制字符串
			String tmpStr = encryptSHA1(content.toString());

			// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
			if (tmpStr != null && tmpStr.equals(signature)) {
				isEqual = true;
			} else {
				isEqual = false;
			}
			content = null;
		} else {
			return isEqual;
		}

		return isEqual;
	}

	/**
	 * SHA1加密
	 * 
	 * @param data
	 * @return
	 */
	public static String encryptSHA1(String data) {
		String str = null;
		try {
			// 获得SHA1摘要算法的 MessageDigest 对象
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			// 使用指定的字节更新摘要
			md.update(data.getBytes());
			// 获得密文
			byte[] bytes = md.digest();
			// 字节数组转化为16进制字符串
			str = bytesToHexString(bytes);

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 字节数组转化为16进制字符串
	 * 
	 * @param bytes
	 * @return
	 */
	public static String bytesToHexString(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		for (int i = 0; i < bytes.length; i++) {
			int temp = bytes[i] & 0xFF;// 与运算，将byte转化为整型
			String hex = Integer.toHexString(temp);// int型转化为16进制字符串
			if (hex.length() < 2) {
				sb.append(0);
			}
			sb.append(hex);
		}
		return sb.toString();
	}
}
